﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace JavaCodeGenerator
{
    /// <summary>
    /// 文本文件存取帮助类
    /// </summary>
    public class TextUtil
    {
        /// <summary>
        /// 从文件中读取所有字符串
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns>字符串</returns>
        public static string ReadString(string filePath)
        {
            try
            {
                return File.ReadAllText(filePath);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 向文件中写入字符串
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="data">要写入的数据</param>
        public static void WriteString(string filePath, string data)
        {
            try
            {
                object obj = new object();
                lock (obj)
                {
                    IfNotExistDirectoryCreate(filePath);
                    File.WriteAllText(filePath, data);
                }

            }
            catch { }
        }

        /// <summary>
        /// 向文件中写入字符串
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="data">要写入的数据</param>
        public static void AppendString(string filePath, string data)
        {
            try
            {
                object obj = new object();
                lock (obj)
                {
                    File.AppendAllText(filePath, data + "\r\n");
                }

            }
            catch { }
        }


        /// <summary>
        /// 从文件中读取字节
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns>字节数组</returns>
        public static byte[] ReadBytes(string filePath)
        {

            try
            {
                return File.ReadAllBytes(filePath);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 将字节写入文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="data">字节数组</param>
        public static void WriteBytes(string filePath, byte[] data)
        {
            try
            {
                object obj = new object();
                lock (obj)
                {
                    IfNotExistDirectoryCreate(filePath);
                    File.WriteAllBytes(filePath, data);
                }
            }
            catch (Exception ex) { throw ex; }

        }

        /// <summary>
        /// 写入准备(确保文件存在,不存在,则创建文件夹及文件)
        /// </summary>
        /// <param name="filePath"></param>
        public static void PrepareWrite(string filePath)
        {
            IfNotExistDirectoryCreate(filePath);
            if (!File.Exists(filePath))
            {
                File.Create(filePath).Close();
            }
        }

        private static void IfNotExistDirectoryCreate(string filePath)
        {
            string[] str = filePath.Split('\\');
            string folder = filePath.Replace(str[str.Length - 1], "");

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

        }

        /// <summary>
        /// 获取文件编码格式
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static Encoding GetEncoding(FileStream stream)
        {
            Encoding bigEndianUnicode = Encoding.Default;
            if ((stream != null) && (stream.Length >= 2L))
            {
                byte num = 0;
                byte num2 = 0;
                byte num3 = 0;
                byte num4 = 0;
                long offset = stream.Seek(0L, SeekOrigin.Begin);
                stream.Seek(0L, SeekOrigin.Begin);
                num = Convert.ToByte(stream.ReadByte());
                num2 = Convert.ToByte(stream.ReadByte());
                if (stream.Length >= 3L)
                {
                    num3 = Convert.ToByte(stream.ReadByte());
                }
                if (stream.Length >= 4L)
                {
                    num4 = Convert.ToByte(stream.ReadByte());
                }
                if ((num == 0xfe) && (num2 == 0xff))
                {
                    bigEndianUnicode = Encoding.BigEndianUnicode;
                }
                else if (((num == 0xff) && (num2 == 0xfe)) && (num3 != 0xff))
                {
                    bigEndianUnicode = Encoding.Unicode;
                }
                else if (((num == 0xef) && (num2 == 0xbb)) && (num3 == 0xbf))
                {
                    bigEndianUnicode = Encoding.UTF8;
                }
                else
                {
                    int num7;
                    int.TryParse(stream.Length.ToString(), out num7);
                    BinaryReader reader = new BinaryReader(stream);
                    if (IsUTF8Bytes(reader.ReadBytes(num7)))
                    {
                        bigEndianUnicode = Encoding.UTF8;
                    }
                }
                stream.Seek(offset, SeekOrigin.Begin);
            }
            return bigEndianUnicode;
        }

        /// <summary>
        /// 获取文件编码格式
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static Encoding GetEncoding(string fileName)
        {
            Encoding encoding = Encoding.Default;
            if (File.Exists(fileName))
            {
                using (FileStream stream = new FileStream(fileName, FileMode.Open))
                {
                    encoding = GetEncoding(stream);
                    stream.Close();
                }
            }
            return encoding;
        }

        private static bool IsUTF8Bytes(byte[] data)
        {
            int num = 1;
            for (int i = 0; i < data.Length; i++)
            {
                byte num2 = data[i];
                if (num == 1)
                {
                    if (num2 >= 0x80)
                    {
                        while (((num2 = (byte)(num2 << 1)) & 0x80) != 0)
                        {
                            num++;
                        }
                        if ((num == 1) || (num > 6))
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    if ((num2 & 0xc0) != 0x80)
                    {
                        return false;
                    }
                    num--;
                }
            }
            if (num > 1)
            {
                throw new Exception("非预期的文件格式");
            }
            return true;
        }

    }
}
